Skip to content

feat(server/sse): Add support for dynamic base paths #214

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged

Conversation

robert-jackson-glean
Copy link
Contributor

@robert-jackson-glean robert-jackson-glean commented Apr 27, 2025

This change introduces the ability to mount SSE endpoints at dynamic paths with variable segments (e.g., /api/{tenant}/sse) by adding a new WithDynamicBasePath option and related functionality. This enables advanced use cases such as multi-tenant architectures or integration with routers that support path parameters.

Key Features:

  • DynamicBasePathFunc: New function type and option (WithDynamicBasePath) to generate the SSE server's base path dynamically per request/session.
  • Flexible Routing: New SSEHandler() and MessageHandler() methods allow mounting handlers at arbitrary or dynamic paths using any router (e.g., net/http, chi, gorilla/mux).
  • Endpoint Generation: GetMessageEndpointForClient now supports both static and dynamic path modes, and correctly generates full URLs when configured.
  • Example: Added examples/dynamic_path/main.go demonstrating dynamic path mounting and usage.
mcpServer := mcp.NewMCPServer("dynamic-path-example", "1.0.0")
sseServer := mcp.NewSSEServer(
  mcpServer,
  mcp.WithDynamicBasePath(func(r *http.Request, sessionID string) string {
    tenant := r.PathValue("tenant")
    return "/api/" + tenant
  }),
  mcp.WithBaseURL("http://localhost:8080"),
)

mux := http.NewServeMux()
mux.Handle("/api/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/api/{tenant}/message", sseServer.MessageHandler())

This is an alternate to #121, the key differences are:

  1. The route parsing is independent of mcp-go and can be done by whatever system the host server already uses (e.g. net/http, gorilla/mux, chi, &c).
  2. This will work well along with Manage tools on a per session basis #179, using a custom session that can be aware of any custom route params and whatnot that might be needed throughout the rest of the system (e.g. in the tool handlers).

Summary by CodeRabbit

  • New Features

    • Added support for dynamic base paths in the SSE server, enabling per-request routing and multi-tenant scenarios.
    • Introduced new handlers for advanced dynamic routing configurations.
    • Provided a new example demonstrating dynamic base path handling with an HTTP server and echo tool.
  • Bug Fixes

    • Improved error handling to prevent incorrect usage when dynamic base paths are enabled.
  • Tests

    • Added comprehensive tests to verify dynamic base path functionality, URL construction, and correct error handling.

Copy link
Contributor

coderabbitai bot commented Apr 27, 2025

Walkthrough

This change introduces dynamic base path support for the SSE server in the mcp-go framework. A new mechanism allows the SSE server's base path to be computed per request using a user-defined function, facilitating multi-tenant or dynamically routed scenarios. The server exposes new handler methods for integration with HTTP routers, and enforces correct usage patterns by returning errors or HTTP 500 responses if static methods are used in dynamic mode. The example and test suite are updated to demonstrate and verify dynamic path handling, including correct endpoint URL generation and error conditions. A new custom error type is added to represent misuse of static path methods with dynamic configuration.

Changes

Files/Paths Change Summary
examples/dynamic_path/main.go Added a new example program demonstrating an HTTP server with dynamic base path handling for SSE, routing requests based on a tenant path segment.
server/sse.go Extended SSE server to support dynamic base path computation via a user-provided function; added new handler methods (SSEHandler, MessageHandler) for router integration; updated endpoint URL generation to use dynamic base paths; modified ServeHTTP and endpoint completion methods to return errors or HTTP 500 when dynamic base path is set; added DynamicBasePathFunc type and WithDynamicBasePath option; added helper normalizeURLPath function.
server/errors.go Added a new custom error type ErrDynamicPathConfig to represent errors when static path methods are used with dynamic base path configuration.
server/sse_test.go Added tests covering dynamic base path scenarios, endpoint URL correctness, error conditions for improper usage, and router-based mounting; improved SSE event reading logic in tests for complete event capture; added table-driven tests for URL path normalization.

Possibly related PRs

  • mark3labs/mcp-go#29: Originally introduced the ServeHTTP method for the SSE server; this PR directly modifies and extends that method to support dynamic base paths.
  • mark3labs/mcp-go#45: Adds static customizable basePath option for SSE server; related but focuses on static rather than dynamic base path handling.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab367d9 and 40c8a68.

📒 Files selected for processing (4)
  • examples/dynamic_path/main.go (1 hunks)
  • server/errors.go (2 hunks)
  • server/sse.go (10 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • server/errors.go
  • server/sse_test.go
  • examples/dynamic_path/main.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (13)
server/sse.go (13)

38-43: Well-documented new feature for dynamic path handling

The new DynamicBasePathFunc type is clearly defined with good documentation explaining its purpose and use cases. The function signature captures all the necessary context (request and sessionID) needed to compute dynamic paths.


76-76: Addition of dynamic base path support

The dynamicBasePathFunc field addition to the SSEServer struct enables the dynamic base path functionality described in the PR objectives. This is properly placed alongside other path-related fields.


110-115: Improved path normalization for static base paths

The WithBasePath function now uses the normalizeURLPath helper, ensuring consistent path formatting for static base paths. This aligns with the retrieved learning about path sanitization to prevent double slashes in URL construction.


117-130: Robust implementation of dynamic base path configuration

The WithDynamicBasePath function intelligently wraps the provided function with path normalization logic, implementing the path sanitization described in the retrieved learning. It correctly handles nil functions, preventing potential runtime errors.


376-391: Enhanced endpoint URL generation with dynamic path support

The GetMessageEndpointForClient method now elegantly handles both static and dynamic path modes, checking for the presence of dynamicBasePathFunc and falling back to the static path when necessary. The proper use of normalizeURLPath ensures consistent path formatting.


508-515: Appropriate error handling for static path methods in dynamic mode

The CompleteSseEndpoint method now correctly returns an error when a dynamic base path is configured, preventing incorrect usage. This maintains separation between static and dynamic path modes.


517-527: Graceful error handling in path completion

The CompleteSsePath method has been updated to properly handle errors from CompleteSseEndpoint, falling back to a normalized path construction. This ensures that the method works correctly in both static and dynamic path modes.


529-535: Consistent error handling for message endpoint in dynamic mode

Similar to CompleteSseEndpoint, the CompleteMessageEndpoint method returns an error when a dynamic base path is configured, maintaining the same pattern across both endpoint types.


537-547: Graceful error handling in message path completion

The CompleteMessagePath method now correctly handles errors from CompleteMessageEndpoint, providing a consistent fallback mechanism similar to CompleteSsePath.


549-576: New handler method enables flexible routing

The SSEHandler method with its comprehensive documentation allows for mounting the SSE endpoint at arbitrary paths using any HTTP router. The code examples provided in the documentation clearly illustrate how to use this with dynamic path segments.


578-605: Companion handler method completes the routing API

The MessageHandler method complements SSEHandler by providing similar functionality for the message endpoint. Together, these methods enable the dynamic routing scenarios described in the PR objectives.


607-612: Clear error handling for incorrect usage

The updated ServeHTTP method now returns a clear error when used with a dynamic base path configuration, enforcing the correct usage pattern of using the specific handler methods instead.


629-645: Robust URL path normalization helper

The new normalizeURLPath function ensures proper URL path formatting by adding a leading slash if missing and removing trailing slashes where appropriate. This implementation aligns with the learning that paths should start with "/" and have no trailing "/" to prevent double slashes.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (7)
examples/dynamic_path/main.go (2)

26-35: Avoid hard-coding the outbound baseURL – derive it from the chosen listen address instead

WithBaseURL("http://localhost:8080") will break if the user changes the -addr flag (:9090, 0.0.0.0:8081, etc.).
Deriving the value once the flag is parsed prevents “wrong endpoint” bugs in copy-pasted examples.

-    server.WithBaseURL("http://localhost:8080"),
+    server.WithBaseURL(fmt.Sprintf("http://localhost%s", addr)),

(If TLS might be enabled in the future, you could inspect addr or add a separate -base-url flag.)


38-40: Router pattern requires Go 1.22 – add a build tag or explicit comment

ServeMux patterns that contain {tenant} only compile/run on Go 1.22+.
A short doc-comment or a //go:build go1.22 guard will save users on earlier versions from a confusing 404.

server/sse.go (3)

331-333: Ensure the initial endpoint event always ends with \n\n

fmt.Fprintf(w, "event: endpoint\ndata: %s\r\n\r\n", endpoint) mixes \r\n and \n.
For consistency with the rest of the stream (eventQueue uses \n\n), prefer \n\n. No functional bug but helps downstream parsers.

- fmt.Fprintf(w, "event: endpoint\ndata: %s\r\n\r\n", endpoint)
+ fmt.Fprintf(w, "event: endpoint\ndata: %s\n\n", endpoint)

478-483: Return errors instead of panicking for library callers

panic here abruptly terminates the program if library users accidentally call the wrong helper.
A safer API is to return an explicit error so callers can decide.

-func (s *SSEServer) CompleteSseEndpoint() string {
-    if s.dynamicBasePathFunc != nil {
-        panic("CompleteSseEndpoint cannot be used with WithDynamicBasePath. Use dynamic path logic in your router.")
-    }
-    return s.baseURL + s.basePath + s.sseEndpoint
-}
+func (s *SSEServer) CompleteSseEndpoint() (string, error) {
+    if s.dynamicBasePathFunc != nil {
+        return "", fmt.Errorf("CompleteSseEndpoint cannot be used together with WithDynamicBasePath")
+    }
+    return s.baseURL + s.basePath + s.sseEndpoint, nil
+}

(Change callers accordingly.)
Panics are still appropriate inside tests, but exported APIs should favour explicit errors.


567-569: ServeHTTP panic could be downgraded to 500 for robustness

If someone accidentally wires the whole server under a dynamic path, the entire process panics. Returning http.StatusInternalServerError (or a log + 500) avoids bringing down shared servers.

server/sse_test.go (2)

946-968: SSEHandlerRequiresDynamicBasePath silently ignores earlier panic expectation

The first two calls (_ = sseServer.SSEHandler()) should be wrapped in require.NotPanics to document the intention; otherwise a panic would skip the rest of the test and the later recover logic never triggers, leading to false positives.


1009-1044: Duplicate code for static vs dynamic endpoint assertions – factor helper

Four almost-identical blocks differ only by constructor options. Extracting a table-driven sub-test improves readability and future maintenance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 33c98f1 and 887b314.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (1 hunks)

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 887b314 to 15e1a5e Compare April 28, 2025 00:10
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
server/sse_test.go (1)

453-469: Improved SSE frame reading with buffered reader loop

Excellent change that addresses the previous review feedback about potential truncation issues. Using a buffered reader loop ensures the complete SSE frame is captured reliably, even on slower systems where the frame might be split across multiple TCP packets.

🧹 Nitpick comments (1)
server/sse_test.go (1)

982-1020: Replace simple buffer read with buffered reader for consistency

While this test case correctly verifies dynamic base path with full URL configuration, it uses a simple buffered read instead of the more robust buffered reader loop introduced earlier in the file.

Consider replacing the simple buffer read with a buffered reader loop for consistency and to prevent potential SSE frame truncation issues:

-		buf := make([]byte, 1024)
-		n, err := resp.Body.Read(buf)
-		if err != nil {
-			t.Fatalf("Failed to read SSE response: %v", err)
-		}
-		endpointEvent := string(buf[:n])
+		reader := bufio.NewReader(resp.Body)
+		var endpointEvent strings.Builder
+		for {
+			line, err := reader.ReadString('\n')
+			if err != nil {
+				t.Fatalf("Failed to read SSE response: %v", err)
+			}
+			endpointEvent.WriteString(line)
+			if line == "\n" || line == "\r\n" {
+				break // End of SSE frame
+			}
+		}
+		endpointEventStr := endpointEvent.String()

Then update the subsequent code to use endpointEventStr instead of endpointEvent.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 887b314 and 15e1a5e.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse.go
🔇 Additional comments (4)
server/sse_test.go (4)

865-957: Well-structured test for dynamic path mounting

This test case thoroughly verifies the new dynamic base path functionality, correctly testing both the SSE endpoint connection and JSON-RPC message communication with tenant-specific paths.

Note that the test uses Go 1.22+ PathValue() function, which should be mentioned in documentation as a dependency requirement.


958-980: Important safety check for dynamic path configuration

Good test ensuring that the API enforces correct usage patterns - SSEHandler and MessageHandler work correctly in both modes, while ServeHTTP properly panics when configured with dynamic paths to prevent misuse.


1022-1057: Comprehensive URL generation test for all configuration combinations

Great test case that verifies the URL generation logic for all combinations of static vs dynamic paths, with and without base URL, and with full URL usage enabled or disabled. This ensures consistent behavior across all configuration patterns.


1059-1070: Important API contract enforcement

Good test verifying that CompleteSseEndpoint correctly panics when used with dynamic base paths, enforcing the API contract and preventing misuse.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 15e1a5e to 252d7d8 Compare April 28, 2025 00:34
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
server/sse.go (1)

368-371: Potential edge case in path concatenation

While path sanitization in WithDynamicBasePath prevents most issues, the direct concatenation of basePath + s.messageEndpoint might still produce unexpected results if s.messageEndpoint doesn't begin with a slash.

Consider using a more robust path joining approach:

-	endpointPath := basePath + s.messageEndpoint
+	// Ensure messageEndpoint starts with a slash for proper concatenation
+	messageEndpoint := s.messageEndpoint
+	if !strings.HasPrefix(messageEndpoint, "/") {
+		messageEndpoint = "/" + messageEndpoint
+	}
+	endpointPath := basePath + messageEndpoint
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15e1a5e and 252d7d8.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (9)
server/sse.go (9)

36-41: Well-defined type for dynamic base path handling

The new DynamicBasePathFunc type is clearly documented and serves an important purpose in enabling multi-tenant and dynamic routing scenarios.


79-80: LGTM - Clear field documentation

The field comment clearly explains the purpose of this function pointer for determining dynamic base paths.


120-136: Good implementation with path sanitization

The implementation of WithDynamicBasePath is robust with proper path sanitization that ensures consistent path formats (adding leading slash when missing and removing trailing slashes). This prevents URL construction issues.


359-374: Clean implementation of dynamic path support in endpoint generation

The updated GetMessageEndpointForClient method properly handles both static and dynamic base paths with a clear implementation. The method intelligently applies the dynamic base path function when available.


485-488: Good defensive programming with clear error guidance

The panic with a clear error message helps prevent misuse of the API by enforcing the correct usage pattern when using dynamic base paths.


501-503: Consistent API enforcement pattern

Consistent with the implementation in CompleteSseEndpoint, ensuring that these methods can't be misused with dynamic base paths.


515-571: Excellent handler abstractions with comprehensive documentation

The new SSEHandler and MessageHandler methods are well-designed and thoroughly documented with example usage. They provide clean abstractions for integrating with various HTTP routers and supporting dynamic path segments.


575-577: Strong API consistency enforcement

The panic in ServeHTTP properly prevents API misuse and clearly guides users toward the correct approach for dynamic path scenarios.


339-340: LGTM - Updated handleSSE to support dynamic paths

Properly updated to pass the request to GetMessageEndpointForClient, enabling dynamic base path resolution.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 252d7d8 to a643f22 Compare April 28, 2025 00:37
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
server/sse.go (1)

364-366: Consider additional validation for dynamic path usage

While you check if dynamicBasePathFunc is non-nil, there's no validation that the returned path is non-empty. An empty path could lead to URL construction issues.

 if s.dynamicBasePathFunc != nil {
     basePath = s.dynamicBasePathFunc(r, sessionID)
+    if basePath == "" {
+        // Log warning or use default
+        basePath = "/"
+    }
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 252d7d8 and a643f22.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (8)
server/sse.go (8)

36-41: Well-documented type for dynamic base path generation

Good definition with clear documentation explaining the purpose and expected behavior of the function type.


79-81: Clean field addition with descriptive comment

The new field for storing the dynamic base path function is well-commented and properly placed in the struct.


120-136: Excellent path sanitization implementation

The implementation correctly normalizes paths by ensuring they start with a slash and don't end with one, preventing potential URL construction issues. This is consistent with the learning from a previous review about preventing double slashes.


359-374: Clean implementation of dynamic endpoint generation

The method correctly handles both static and dynamic paths, with proper fallback and consistent URL construction. The implementation is straightforward and maintains backward compatibility.


485-489: Good enforcement of usage patterns

Appropriate panic messages when attempting to use static methods with dynamic paths, guiding users toward the correct pattern. This helps prevent subtle bugs that could arise from mixing the two approaches.

Also applies to: 501-504


515-542: Well-documented handler for SSE endpoint

The SSEHandler method has excellent documentation with clear examples that show how to use it with dynamic paths. The examples are particularly helpful for showing the integration with routers.


544-571: Well-documented handler for message endpoint

Similar to the SSE handler, the documentation is thorough with relevant examples. The consistent approach between both handlers makes the API intuitive to use.


575-577: Clear enforcement of the correct usage pattern

The panic message explicitly directs users to the appropriate methods for dynamic path scenarios, preventing misuse of the API.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from a643f22 to 86cebe8 Compare April 28, 2025 01:20
@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from 86cebe8 to 4abd640 Compare April 29, 2025 21:42
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
server/sse.go (1)

368-371: Potential path construction issue with endpointPath

The current concatenation basePath + s.messageEndpoint might lead to double slashes if s.messageEndpoint starts with a slash, or missing slashes if it doesn't.

Consider using string concatenation that ensures exactly one slash between path segments:

-	endpointPath := basePath + s.messageEndpoint
+	// Ensure exactly one slash between segments
+	if strings.HasSuffix(basePath, "/") {
+		if strings.HasPrefix(s.messageEndpoint, "/") {
+			endpointPath = basePath + s.messageEndpoint[1:]
+		} else {
+			endpointPath = basePath + s.messageEndpoint
+		}
+	} else {
+		if strings.HasPrefix(s.messageEndpoint, "/") {
+			endpointPath = basePath + s.messageEndpoint
+		} else {
+			endpointPath = basePath + "/" + s.messageEndpoint
+		}
+	}

Or more simply with path cleaning:

+import "path"

 	// ...
-	endpointPath := basePath + s.messageEndpoint
+	endpointPath := path.Join(basePath, s.messageEndpoint)
+	// path.Join strips the leading slash; restore it
+	if !strings.HasPrefix(endpointPath, "/") {
+		endpointPath = "/" + endpointPath
+	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86cebe8 and 4abd640.

📒 Files selected for processing (3)
  • examples/dynamic_path/main.go (1 hunks)
  • server/sse.go (9 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🔇 Additional comments (10)
server/sse.go (10)

36-41: Well-documented new type DynamicBasePathFunc

This new type definition is well-documented with a clear description of its purpose and expected usage. The function signature is appropriately designed to accept both the HTTP request and session ID as parameters, providing the necessary context for computing dynamic paths.


79-80: Well-placed field addition for dynamic base path function

The SSEServer struct is appropriately extended with the dynamicBasePathFunc field to store the user-provided function. The comment accurately describes its purpose.


120-136: Good implementation of path sanitization in WithDynamicBasePath

The implementation correctly wraps the user-provided function to ensure path normalization (adding leading slash if missing and removing trailing slash). This aligns with the retrieved learning and prevents URL construction issues.


339-340: Correct update to handleSSE for dynamic base path support

The code now correctly passes the HTTP request to GetMessageEndpointForClient, which is necessary for dynamic base path resolution in the initial endpoint event.


362-374: Robust implementation of GetMessageEndpointForClient

The method now properly handles both static and dynamic base paths. The logic is clear and correctly applies the configured options, including the full URL usage flag.


486-488: Clear boundary enforcement in CompleteSseEndpoint

The panic message clearly indicates that this method shouldn't be used with dynamic base paths and suggests the correct approach.

However, based on a previous review comment, there was a discussion about avoiding panics in favor of standard Go error patterns.

Consider using an error return instead of a panic, as discussed in previous feedback:

-func (s *SSEServer) CompleteSseEndpoint() string {
+func (s *SSEServer) CompleteSseEndpoint() (string, error) {
 	if s.dynamicBasePathFunc != nil {
-		panic("CompleteSseEndpoint cannot be used with WithDynamicBasePath. Use dynamic path logic in your router.")
+		return "", fmt.Errorf("CompleteSseEndpoint cannot be used with WithDynamicBasePath; use dynamic path logic in your router")
 	}
-	return s.baseURL + s.basePath + s.sseEndpoint
+	return s.baseURL + s.basePath + s.sseEndpoint, nil
}

501-503: Clear boundary enforcement in CompleteMessageEndpoint

Similar to CompleteSseEndpoint, this method uses a panic to clearly indicate that it's incompatible with dynamic base paths.

The same concern applies here regarding the use of panics.

Consider using an error return instead of a panic, as discussed in previous feedback:

-func (s *SSEServer) CompleteMessageEndpoint() string {
+func (s *SSEServer) CompleteMessageEndpoint() (string, error) {
 	if s.dynamicBasePathFunc != nil {
-		panic("CompleteMessageEndpoint cannot be used with WithDynamicBasePath. Use dynamic path logic in your router.")
+		return "", fmt.Errorf("CompleteMessageEndpoint cannot be used with WithDynamicBasePath; use dynamic path logic in your router")
 	}
-	return s.baseURL + s.basePath + s.messageEndpoint
+	return s.baseURL + s.basePath + s.messageEndpoint, nil
}

515-543: Well-documented SSEHandler method with clear usage examples

This new method provides a clear, clean interface for mounting the SSE handler at any path. The documentation is excellent, with helpful examples and important usage notes. The implementation is simple and delegates to the existing handler function.


544-571: Well-documented MessageHandler method with clear usage examples

Like the SSEHandler method, this provides a clean interface for mounting the message handler. The documentation is clear and includes helpful examples that match those in the SSEHandler documentation for consistency.


575-577: Clear boundary enforcement in ServeHTTP

The method correctly prevents the use of ServeHTTP with dynamic base paths, directing users to the appropriate alternative methods.

However, similar to the other methods, the use of panic here could be reconsidered.

Consider handling this case with an error response instead of a panic:

func (s *SSEServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.dynamicBasePathFunc != nil {
-		panic("ServeHTTP cannot be used with WithDynamicBasePath. Use SSEHandler/MessageHandler and mount them with your router.")
+		http.Error(w, "ServeHTTP cannot be used with WithDynamicBasePath. Use SSEHandler/MessageHandler and mount them with your router.", http.StatusInternalServerError)
+		return
	}
	// Rest of the method...
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 304fe1a and ebb4e67.

📒 Files selected for processing (4)
  • examples/dynamic_path/main.go (1 hunks)
  • server/errors.go (2 hunks)
  • server/sse.go (7 hunks)
  • server/sse_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • server/errors.go
  • examples/dynamic_path/main.go
  • server/sse_test.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
server/sse.go (1)
Learnt from: robert-jackson-glean
PR: mark3labs/mcp-go#214
File: server/sse.go:0-0
Timestamp: 2025-04-28T00:14:49.237Z
Learning: The SSE server in mcp-go implements path sanitization within the `WithDynamicBasePath` function that ensures the dynamic base path starts with "/" and has no trailing "/" to prevent double slashes in URL construction.
🧬 Code Graph Analysis (1)
server/sse.go (2)
mcp/types.go (1)
  • Request (103-116)
server/errors.go (1)
  • ErrDynamicPathConfig (27-29)
🔇 Additional comments (8)
server/sse.go (8)

36-41: Well-designed interface for dynamic base path generation

The DynamicBasePathFunc type definition provides a clear and flexible interface for generating base paths dynamically. The documentation clearly explains the purpose and expected return values.


79-81: Good field documentation for the dynamic base path function

The comment clearly indicates the purpose of this field in the SSEServer struct.


120-136: Excellent path sanitization implementation

The path sanitization logic ensures base paths always start with a leading slash and have no trailing slash, preventing URL construction issues. This implementation matches the learnings from previous PRs and properly handles nil functions.


485-490: Good error handling for incompatible dynamic configuration

Returning a specialized error when attempting to use static path methods with dynamic configuration is a clean approach that provides clear guidance to users.


504-509: Consistent error handling pattern

The error handling approach is consistent with CompleteSseEndpoint, providing a unified experience across the API.


523-550: Comprehensive documentation with practical examples

The documentation for SSEHandler is excellent - it clearly explains the purpose, usage scenarios, and provides concrete examples. The emphasis on using WithDynamicBasePath with these handlers is important for correctness.


552-579: Consistent handler implementation and documentation

The MessageHandler implementation follows the same pattern as SSEHandler, with equally thorough documentation.


583-586: Appropriate enforcement of usage patterns

Returning an HTTP 500 error with a clear message when attempting to use ServeHTTP with dynamic configuration is a good way to enforce correct usage patterns and guide users to the appropriate methods.

@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from ebb4e67 to ab367d9 Compare May 1, 2025 11:50
This change introduces the ability to mount SSE endpoints at dynamic
paths with variable segments (e.g., `/api/{tenant}/sse`) by adding a new
`WithDynamicBasePath` option and related functionality. This enables
advanced use cases such as multi-tenant architectures or integration
with routers that support path parameters.

Key Features:

* DynamicBasePathFunc: New function type and option
  (WithDynamicBasePath) to generate the SSE server's base path
  dynamically per request/session.
* Flexible Routing: New SSEHandler() and MessageHandler() methods allow
  mounting handlers at arbitrary or dynamic paths using any router
  (e.g., net/http, chi, gorilla/mux).
* Endpoint Generation: GetMessageEndpointForClient now supports both
  static and dynamic path modes, and correctly generates full URLs when
  configured.
* Example: Added examples/dynamic_path/main.go demonstrating dynamic
  path mounting and usage.

```go
mcpServer := mcp.NewMCPServer("dynamic-path-example", "1.0.0")
sseServer := mcp.NewSSEServer(
  mcpServer,
  mcp.WithDynamicBasePath(func(r *http.Request, sessionID string) string {
    tenant := r.PathValue("tenant")
    return "/api/" + tenant
  }),
  mcp.WithBaseURL("http://localhost:8080"),
)

mux := http.NewServeMux()
mux.Handle("/api/{tenant}/sse", sseServer.SSEHandler())
mux.Handle("/api/{tenant}/message", sseServer.MessageHandler())
```
Replace manual path manipulation with a dedicated normalizeURLPath function
that properly handles path joining while ensuring consistent formatting.
The function:

- Always starts paths with a leading slash
- Never ends paths with a trailing slash (except for root path "/")
- Uses path.Join internally for proper path normalization
- Handles edge cases like empty segments, double slashes, and parent references

This eliminates duplicated code and creates a more consistent approach to
URL path handling throughout the SSE server implementation. Comprehensive
tests were added to validate the function's behavior.
@robert-jackson-glean robert-jackson-glean force-pushed the rwjblue/push-ysoppsqxnkmy branch from ab367d9 to 40c8a68 Compare May 1, 2025 12:24
@ezynda3 ezynda3 merged commit 4a1010e into mark3labs:main May 1, 2025
2 checks passed
@robert-jackson-glean robert-jackson-glean deleted the rwjblue/push-ysoppsqxnkmy branch May 1, 2025 12:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants